package com.catering.until;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.catering.dao.YqAdminDao;
import com.catering.dao.YqLogInfoDao;
import com.catering.entity.LogInfo;
import com.catering.entity.YqAdmin;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.HashMap;

@Aspect
@Component
public class LogAspect {
	@Autowired
	private YqLogInfoDao logInfoDao;
	@Autowired
	private YqAdminDao adminDao;
	/** 
     * 日志业务逻辑方法切入点 
     */ 
	@Pointcut("@annotation(com.catering.until.Log)")
	public void logInfo() {  }  
      
	
    /** 
     * 管理员添加操作日志(后置通知) 
     * @param joinPoint 
     * @param rtv 
     * @throws Throwable 
     */  
    @AfterReturning(value="logInfo()", argNames="rtv", returning="rtv")  
    public void insertServiceCallCalls(JoinPoint point, Object rtv) throws Throwable{  
    	try {
			HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
	        MethodSignature methodSignature = (MethodSignature)point.getSignature();
	        Method method = methodSignature.getMethod();
	        //String userName = Tools.getRequest().getHeader("userName");
	        String token = request.getParameter("token");
	        if(CommonUtils.checkNull(token)) token = request.getHeader("token");
	    	Log slog = method.getAnnotation(Log.class);
	    	//判断参数  
	        if(CommonUtils.checkNull(point.getArgs())) return;  
	        //获取方法名  
	        //String methodName = joinPoint.getSignature().getName();  
	        //获取操作内容  
	        Object args = point.getArgs()[0];
	        String className = null;
	        LogInfo log = new LogInfo();
	        if(args != null) {
	        	className = point.getArgs()[0].getClass().getName();
	        	className = className.substring(className.lastIndexOf(".") + 1);
	        	log.setModule(className.toLowerCase());
	        }else {
	        	log.setModule(className);
	        }
	        String opContent = adminOptionContent(point.getArgs(), slog.operation());  
	        //创建日志对象  
	        log.setSysId(CommonUtils.getUuid());
	        System.out.println("获取的userName"+request.getHeader("userName"));
	        if("4".equals(slog.type())) {
	    		if(CommonUtils.checkNoNull(token))log.setUserName(adminDao.selectOne(new QueryWrapper<YqAdmin>().eq("token", token)).getUserName());
	    		else log.setUserName(IpUtil.getIpAddr(request));
	        }else {
	        	log.setUserName(request.getHeader("userName"));
	        }
	        log.setMethod(request.getRequestURI());
	        //操作内容  
	        log.setContent(opContent);
	        log.setType(slog.type());
	        ResultData rt = (ResultData)rtv;
	        log.setResult("{请求状态："+rt.getCode() + " || 请求结果："+ rt.getMsg() + " || 请求数据："+ rt.getData() +"}");
	        log.setRemark(slog.remark());
	        //操作
	        log.setOperation(slog.operation());
	        log.setUserIp(IpUtil.getIpAddr(request));
			logInfoDao.insert(log);
    	}catch (Exception e) {
			e.printStackTrace();
		}
    }  
    
    
	/**
	 * 使用Java反射来获取被拦截方法(insert、update)的参数值， 将参数值拼接为操作内容
	 */
	@SuppressWarnings("unchecked")
	private String adminOptionContent(Object[] args, String type) {
		if (args == null) {
			return null;
		}
		StringBuffer sb = new StringBuffer();
		Object info = args[0];
		String className = null;
		if(info != null) {
			className = info.getClass().getName();
			className = className.substring(className.lastIndexOf(".") + 1);
			sb.append(type+" 属性名和值：");
			HashMap map = new HashMap();
			// 遍历方法，判断get方法
			for(Object str : args) map = JSONObject.parseObject(JSON.toJSONString(str), HashMap.class);
			for(Object key : map.keySet()) sb.append(" " + key + "  -->  " + map.get(key) + "  ||  ");
		}
		return sb.toString();
	}
	
	public String returnStatus(String status) {
		if(status.equals("0")) {
			return "成功";
		}else {
			return "失败";
		}
	}
}
